package oauth

import (
	"context"
	model "micro-oauth/datamodels"
	"micro-oauth/datamodels/autherror"
	"micro-oauth/datamodels/params"
)

func (s *OauthServiceImpl) AddRolePermissionInfos(ctx context.Context, roleId uint64, req *params.RoleAddPermissionInfosRequest) autherror.HexError {
	partnerId := ctx.Value("partner_id").(uint64)
	role := s.repoService.GetRoleById(roleId)
	if role == nil {
		return autherror.NotFound("can't find role")
	}
	if role.PartnerId != partnerId {
		return autherror.PermissionDenied("no partner permission")
	}
	var permissionInfos = make([]*model.RolePermissionInfo, 0)
	if len(req.PermissionInfos) != 0 {
		for _, pItem := range req.PermissionInfos {
			permissionInfos = append(permissionInfos, &model.RolePermissionInfo{
				RoleId:       roleId,
				PermissionId: pItem.PermissionId,
				NeedAuth:     pItem.NeedAuth,
			})
		}
	}
	err := s.repoService.ReplaceRolePermissionInfos(role, permissionInfos)
	if err != nil {
		return autherror.DBError(err.Error())
	}
	return nil
}
